<?php

class Rcp_AdImport_EmployeeImport {
	
	const SERVER1_NAME = 'skodaauto';
	const SERVER2_NAME = 'kulczyktradex';
	
	private $ldap;
	private $config;
	
	function __construct($serverConfig) {
		$this->config = $serverConfig->config;
		$this->ldap = new Zend_Ldap($serverConfig->options->toArray());
	}
	
	public function start() {
		$this->ldap->bind($this->config->username, $this->config->password);
		$result = $this->ldap->search($this->config->filter);
		
		$con = Propel::getConnection();
		$con->beginTransaction();
		try {
			RcpUsersQuery::create()->filterByDeleted(null, Criteria::ISNULL)->update(array('Deleted' => new DateTime('now')), $con);
			$users = EmpevalUsersQuery::create()
			->find($con)
			->getArrayCopy('ExtId');
			foreach ($result as $item) {
				if (!key_exists('employeeid', $item) || !key_exists($this->getValue('employeeid', $item), $users))
					continue;
				
				$user = $users[$this->getValue('employeeid', $item)];
				$user->setDeleted(null);
				
				if ($this->getValue('mail', $item) != null)
					$user->setEmail($this->getValue('mail', $item));
				if ($this->getValue('givenname', $item) != null)
					$user->setFname($this->getValue('givenname', $item));
				if ($this->getValue('sn', $item) != null)
					$user->setLname($this->getValue('sn', $item));
				if ($this->getValue('userprincipalname', $item) != null) {
					$userprincipalname = $this->getValue('userprincipalname', $item);
					if (self::SERVER1_NAME == $this->config->servername)
						$user->setAdLogin1($userprincipalname);
					else
						$user->setAdLogin2($userprincipalname);
				}
				if ($this->getValue('mobile', $item) != null)
					$user->setMobile(str_replace(' ', '', trim($this->getValue('mobile', $item))));
				if ($this->getValue('samaccountname', $item) != null) {
					$samaccountname = $this->getValue('samaccountname', $item);
					if (self::SERVER1_NAME == $this->config->servername)
						$user->setAdAccountNmae1($samaccountname);
					else
						$user->setAdAccountNmae2($samaccountname);
				}
				$user->save($con);
			}
			$con->commit();
		} catch (Exception $e) {
			$con->rollBack();
			throw $e;
		}
	}
	
	private function getValue($key, $item, $reset = true) {
		if (!key_exists($key, $item))
			return null;
		return ($reset) ? reset($item[$key]) : $item[$key];
	}
	
}